﻿using Entity;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApiDbContext db;
        public UserController(ApiDbContext context)
        {
            db = context;
        }

        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result Get() {
            Result result = new Result();

            var resulrData= db.EntityUser.ToList<EntityUser>();
            result.Data = resulrData;
            result.Code = 200;
            result.Author = "444274941@qq.com";
            return result;
        }

        /// <summary>
        /// 根据ID获取数据
        /// ResultFull 风格
        /// http://localhost:5291/api/user?Id=4387e222-ec4b-4bdc-83f0-705791bdd728
        ///  http://localhost:5291/api/user/4387e222-ec4b-4bdc-83f0-705791bdd728
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// /// Path:路径参数
        [HttpGet("{Id}/{userName}")]
        public Result Get(Guid Id,string userName)
        {
            Result result = new Result();
            // where: 过滤行
            // select: 过滤列
            // tolist(): 筛选一个范围的数据(集合)
            // FirstOrDefault(): 筛选第一条符合条件的数据行(对象)
            // <> : 确认数据类型( 泛型 )

            EntityUser? resulrData = db.EntityUser.Where(w=>w.Id==Id).FirstOrDefault<EntityUser>();
            if(resulrData==null)
            {
                result.Code = 404;                
            }
            else
            {
                result.Code = 200;
                result.Data = resulrData;
            }
            return result;
        }
        [HttpPost]
        public Result AddUser([FromBody] EntityUser user)
        {
            Result result = new Result();
            db.EntityUser.Add(user);
            //savechanges:返回值为影响的行数；
            //如果值为0，表示，没有任何数据被修改
            //大于0 表示有至少，1行被修改
            result.Data = db.SaveChanges();
            return result;
        }
        [HttpDelete]
        public Result DelUser(Guid id)
        {
            Result result = new Result();
            EntityUser user = db.EntityUser.Where(w=>w.Id==id).SingleOrDefault();
            if(user!=null)
                db.EntityUser.Remove(user);
            result.Data = db.SaveChanges();
            return result;
        }
        [HttpPut]
        public Result UpUse([FromBody]EntityUser user)
        {
            Result result = new Result();
            db.EntityUser.Update(user);
            result.Data= db.SaveChanges();
            return result;
        }
    }
}
